/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-26 15:32:46   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zx.cloud.ApiVersion;
import com.zx.cloud.Shift;
import com.zx.cloud.common.filter.CurrentUserId;
import com.zx.cloud.common.filter.IgnoreAuth;
import com.zx.cloud.domain.ScheduleJob;
import com.zx.cloud.domain.ScheduleJobHistory;
import com.zx.cloud.model.request.QuartzJobRequest;
import com.zx.cloud.model.response.ObjectDataResponse;
import com.zx.cloud.model.response.Response;
import com.zx.cloud.service.ScheduleJobHistoryService;
import com.zx.cloud.service.ScheduleJobService;
import com.zx.cloud.util.Page;

import io.swagger.annotations.ApiOperation;

/**
 * 定时任务
 */
@RestController
@RequestMapping(value = ApiVersion.QUARTZ_V1_PREFIX+"/job")
public class ScheduleJobController {

	
	@Autowired
	private ScheduleJobService scheduleJobService;
	@Autowired
	private ScheduleJobHistoryService scheduleJobHistoryService;
	
	@IgnoreAuth
	@ApiOperation(value = "查找定时任务历史记录", notes = "查找定时任务历史记录")
	@RequestMapping(value = "findHistory", method = RequestMethod.POST)
	@ResponseBody
	public Response findHistory(@CurrentUserId Long userId,@RequestBody ScheduleJobHistory scheduleJobHistory){
		Page<ScheduleJobHistory> datas=scheduleJobHistoryService.page(scheduleJobHistory);
		return new ObjectDataResponse<Page<ScheduleJobHistory>>(datas);
	}
	
	@IgnoreAuth
	@RequestMapping(value = "/find", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查找定时任务", notes = "查找定时任务")
	public ObjectDataResponse<List<ScheduleJob>> find() throws SchedulerException {
		List<ScheduleJob> scheduleEntities = scheduleJobService.getAllScheduleJob();
		return new ObjectDataResponse<List<ScheduleJob>>(scheduleEntities);
	}

	 /**
     * 暂停任务
     */
	@IgnoreAuth
    @ResponseBody
    @RequestMapping(value ="/stopJob", method = RequestMethod.POST)
    @ApiOperation(value = "暂停定时任务", notes = "暂停定时任务")
    public ObjectDataResponse<Boolean> stop(@RequestBody QuartzJobRequest quartzJobRequest) {
    	if (StringUtils.isEmpty(quartzJobRequest.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(quartzJobRequest.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
    	try {
            scheduleJobService.stopJob(quartzJobRequest.getJobName(), quartzJobRequest.getJobGroup());
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "添加定时任务错误,请重试!");
        }
        return new ObjectDataResponse<Boolean>(Boolean.TRUE);
    }
	
	/**
     * 修改定时任务
     */
	@IgnoreAuth
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改定时任务", notes = "修改定时任务")
	public ObjectDataResponse<Boolean> update(@RequestBody ScheduleJob scheduleJob) throws ClassNotFoundException, SchedulerException {
		if (StringUtils.isEmpty(scheduleJob.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getCronExpression())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"CronExpression必传!");
		}
		try {
            scheduleJobService.modifyTrigger(scheduleJob.getJobName(), scheduleJob.getJobGroup(),scheduleJob.getCronExpression());
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "修改定时任务错误,请重试!");
        }
		return new ObjectDataResponse<Boolean>(Boolean.TRUE);
	}
	
    /**
     * 添加任务
     */
	@IgnoreAuth
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加定时任务", notes = "添加定时任务")
	public ObjectDataResponse<Boolean> add(@RequestBody ScheduleJob scheduleJob) throws ClassNotFoundException, SchedulerException {
		if (StringUtils.isEmpty(scheduleJob.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getClassName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"ClassName必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getMethodName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"MethodName必传!");
		}
		if (StringUtils.isEmpty(scheduleJob.getCronExpression())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"CronExpression必传!");
		}
		try {
			boolean f = CronExpression.isValidExpression(scheduleJob.getCronExpression());
			if (!f) {
				Shift.fatal(StatusCode.INVALID_MODEL_FIELDS, "cron表达式有误，不能被解析！");
			}
			scheduleJob.setStatus("1");
			scheduleJobService.add(scheduleJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "添加定时任务错误,请重试!");
        }
		return new ObjectDataResponse<Boolean>(Boolean.TRUE);
	}

	/**
	 * 删除定时任务
	 * @param quartzJobRequest
	 * @return
	 */
	@IgnoreAuth
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除定时任务", notes = "删除定时任务")
	public ObjectDataResponse<Boolean> delete(@RequestBody QuartzJobRequest quartzJobRequest) {
		if (StringUtils.isEmpty(quartzJobRequest.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(quartzJobRequest.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
		try {
            scheduleJobService.delJob(quartzJobRequest.getJobName(), quartzJobRequest.getJobGroup());
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "删除定时任务错误,请重试!");
        }
		 return new ObjectDataResponse<Boolean>(Boolean.TRUE);
	}
	
	/**
     * 立即运行一次
     */
	@IgnoreAuth
	@RequestMapping(value = "/startNow", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "立即运行一次定时任务", notes = "立即运行一次定时任务")
	public ObjectDataResponse<Boolean> startNowJob(@RequestBody QuartzJobRequest quartzJobRequest) {
		if (StringUtils.isEmpty(quartzJobRequest.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(quartzJobRequest.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
		try {
            scheduleJobService.startNowJob(quartzJobRequest.getJobName(), quartzJobRequest.getJobGroup());
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "立即运行一次定时任务错误,请重试!");
        }
		 return new ObjectDataResponse<Boolean>(Boolean.TRUE);
	}
	
	/**
     * 恢复
     */
	@RequestMapping(value = "/resume", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "恢复定时任务", notes = "恢复定时任务")
	public ObjectDataResponse<Boolean> resume(@RequestBody QuartzJobRequest quartzJobRequest) {
		if (StringUtils.isEmpty(quartzJobRequest.getJobName())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobName必传!");
		}
		if (StringUtils.isEmpty(quartzJobRequest.getJobGroup())) {
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"JobGroup必传!");
		}
		try {
            scheduleJobService.restartJob(quartzJobRequest.getJobName(), quartzJobRequest.getJobGroup());
        } catch (SchedulerException e) {
            e.printStackTrace();
    		Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR, "恢复定时任务错误,请重试!");
        }
		 return new ObjectDataResponse<Boolean>(Boolean.TRUE);
	}

}
